//
//  YLCWebLabelCell.m
//  LinYa
//
//  Created by 初程程 on 2018/5/3.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCWebLabelCell.h"
@interface YLCWebLabelCell()
@property (weak, nonatomic) IBOutlet UILabel *webLabel;

@property (nonatomic,strong) UIWebView * webView;
@end
@implementation YLCWebLabelCell

- (void)awakeFromNib {
    [super awakeFromNib];
    _webLabel.numberOfLines = 0;
    
    _webView = [[UIWebView alloc]init];
    
    [self addSubview:_webView];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    _webView.frame = CGRectMake(0, 0, self.frameWidth, self.frameHeight);
}
- (void)setContent:(NSString *)content{
    NSString *contentString = [self htmlEntityDecode:[NSString stringWithFormat:@"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/><style>img{max-width:%.0fpx !important;}</style>%@",kScreenWidth-40,content]];
//    NSAttributedString *attrStr = [self attributedStringWithHTMLString:contentString];
//    _webLabel.attributedText = attrStr;

    [_webView loadHTMLString:contentString baseURL:nil];
}
- (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"&" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@";" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                               NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    
    NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    
    return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
//将 &lt 等类似的字符转化为HTML中的“<”等
- (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"
    
    return string;
}
@end
